package com.itheima.nio.buffer.demo06;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.concurrent.TimeUnit;

public class NioServerDemo06 {

    public static void main(String[] args) throws IOException, InterruptedException {

        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.socket().bind(new InetSocketAddress(7878));
        serverSocketChannel.configureBlocking(false);
//        TimeUnit.SECONDS.sleep(10);
//        SocketChannel socketChannel = serverSocketChannel.accept();
////        TimeUnit.SECONDS.sleep(10);
//        System.out.println(socketChannel);
//        TimeUnit.SECONDS.sleep(10);
//        if (socketChannel != null){
//            socketChannel.close();
//        }
        while (true){
            SocketChannel socketChannel = serverSocketChannel.accept();
            if (socketChannel != null){
                socketChannel.configureBlocking(false);
                System.out.println("1---------");
                System.out.println(socketChannel);
                System.out.println("2-------");
                ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                int read = socketChannel.read(byteBuffer);
                while (read > 0){
                    byteBuffer.flip();
                    byte[] bytes = byteBuffer.array();
                    System.out.println(new String(bytes, 0, read));
                    byteBuffer.clear();
                    read = socketChannel.read(byteBuffer);
                }
                ByteBuffer byteBuffer1 = ByteBuffer.wrap("收到了".getBytes("UTF-8"));
                socketChannel.write(byteBuffer1);
                socketChannel.close();
            }
        }
    }
}
